﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;

namespace Application
{
    /// <summary>
    /// 序列工具
    /// </summary>
    public class SerializeHelper
    {
        /// <summary>
        /// 将对象序列化为文件流
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="knownTypes"></param>
        /// <param name="t"></param>
        public static void Serialize<T>(string path, List<Type> knownTypes, T t)
        {
            DataContractSerializer ser = new DataContractSerializer(typeof(T), knownTypes);
            FileStream fs = new FileStream(path, FileMode.Create);
            using (fs)
            {
                ser.WriteObject(fs, t);
            }
        }
        /// <summary>
        /// 将文件反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="knownTypes"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string path, List<Type> knownTypes)
        {
            DataContractSerializer ser = new DataContractSerializer(typeof(T), knownTypes);
            FileStream fs = new FileStream(path, FileMode.Open);
            T obj = default(T);
            using (fs)
            {
                obj = (T)ser.ReadObject(fs);
            }
            return obj;
        }
    }
}
